package com.hxf.dao;

import java.io.Serializable; 
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 
import org.springframework.stereotype.Repository;
  
import com.hxf.common.PublicUtil;
import com.hxf.dto.BaseDto;
import com.hxf.dto.ReturnData;
import com.hxf.dto.TmpTableDto;
import com.hxf.exception.DaoLevelException;

/**
 * DAO公共实现类
 * @author tengyicheng
 * @version [1.0, 2013/09/22]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@SuppressWarnings("unchecked")
@Repository("baseDao")
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao {

	@Override
	public void create(BaseDto entity) throws DaoLevelException {
		super.getHibernateTemplate().save(entity);
	}

	@Override
	public void delete(BaseDto entity) throws DaoLevelException { 
		super.getHibernateTemplate().delete(entity);
	}
	
	@Override
	public List findBy(String hql) throws DaoLevelException {
		return super.getHibernateTemplate().find(hql);
	}
	
	@Override
	public ReturnData findBy(final String hql,final Integer targetPage,final Integer pageSize) throws DaoLevelException {
		ReturnData rd = new ReturnData();
		 if (targetPage > 0) {
			 if(!(pageSize==1&&targetPage==1)){
				 	//查询总行数
					rd.setRecordcount(getCount(hql));
			 }else{
					rd.setRecordcount(1);
			 } 
		 }
		 Query query = super.getSession().createQuery(hql);//hql 语句查询
		 query.setFirstResult((targetPage - 1) * pageSize);
		 query.setMaxResults(pageSize); 
		 rd.setResultlist(query.list()); 
		 
		return rd;
	}
	
	@Override
	public ReturnData exeSQLList(final String sql,final Integer targetPage,final Integer pageSize) throws DaoLevelException {
		ReturnData rd = new ReturnData();
		 if (targetPage > 0) {
			 if(!(pageSize==1&&targetPage==1)){
				 	//查询总行数
					rd.setRecordcount(getCountSQL(sql));
			 }else{
					rd.setRecordcount(1);
			 } 
		 }
		 Query query = super.getSession().createSQLQuery(sql);//执行 sql 语句
		 query.setFirstResult((targetPage - 1) * pageSize);
		 query.setMaxResults(pageSize); 
		 rd.setResultlist(query.list()); 
		 
		return rd;
	}
	
	@Override
	public void flush() throws DaoLevelException {
		super.getHibernateTemplate().flush();
	}
	 
	@Override
	public BaseDto load(Class clazz, Serializable id) throws DaoLevelException {		
		return (BaseDto)super.getHibernateTemplate().load(clazz, id);
	}

	@Override
	public void saveOrUpdate(BaseDto entity) throws DaoLevelException {
		super.getHibernateTemplate().saveOrUpdate(entity);
	}

	@Override
	public void update(BaseDto entity) throws DaoLevelException {
		super.getHibernateTemplate().update(entity);
	}

	@Override
	public BaseDto get(Class clazz, Serializable id) throws DaoLevelException {
		return (BaseDto)super.getHibernateTemplate().get(clazz, id); 
	}
	
	@Autowired
	public void setSf(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	@Override
	public Integer getMaxId(String idName, String className)throws DaoLevelException {
		//查询数据表是否存在数据
		List<Long> countList = super.getHibernateTemplate().find("select count("+idName+")   from "+className);
		if (PublicUtil.isNotNull(countList) && countList.size() > 0 && countList.get(0) > 0) {
			//查询最大ID
			List<Integer> list = super.getHibernateTemplate().find("select max("+idName+")   from "+className);
			if (PublicUtil.isNotNull(list) && list.size() > 0) {
				return list.get(0);
			}
		}
		return 0; 
	}

	@Override
	public List exeHql(String hql) throws DaoLevelException { 
		return  this.getSession().createQuery(hql).list();
	}

	@Override
	public List exeSQLList(String sql) throws DaoLevelException { 
		return this.getSession().createSQLQuery(sql).list();
	}
	
	@Override
	public int executeUpdateByHql(String hql) throws DaoLevelException {
		return this.getSession().createQuery(hql).executeUpdate();
	}
	
	@Override
	public int executeUpdateBySql(String sql) throws DaoLevelException {
		return this.getSession().createSQLQuery(sql).executeUpdate();
	}

	/*
	 * Hql 语句
	 */
	@Override
	public int getCount(String queryStr) throws DaoLevelException {
		
		int length = queryStr.indexOf("order by") > 0 ? queryStr
				.indexOf("order by") : queryStr.length();
				
		String hql = "select count(*) "
				+ queryStr.substring(queryStr.indexOf("from"), length);
		System.out.println("hql:"+hql);
		int size = 0;
		
		try {
			size = getRecordCount(hql);
		} catch (DaoLevelException e) {
			logger.debug(e);
		}
		return size; 
	}
	
	
	public int getCountSQL(String queryStr) throws DaoLevelException {
		
		int length = queryStr.indexOf("order by") > 0 ? queryStr
				.indexOf("order by") : queryStr.length();
				
		String hql = "select count(*) "
				+ queryStr.substring(queryStr.indexOf("from"), length);
		System.out.println("hql:"+hql);
		int size = 0;
		
		try {
			size = getRecordCountSQL(hql);
		} catch (DaoLevelException e) {
			logger.debug(e);
		}
		return size; 
	}

	public int getRecordCountSQL(String queryStr) throws DaoLevelException {
		Query query = this.getSession().createSQLQuery(queryStr);
		Object obj = query.list().get(0); 
		Integer recordCount = 0;
		if (obj != null) {
			recordCount = new Integer(obj.toString());
		} else {
			recordCount = 0;
		}
		return recordCount;
	}
	
	@Override
	public int getRecordCount(String queryStr) throws DaoLevelException {
		Query query = this.getSession().createQuery(queryStr);
		Object obj = query.list().get(0); 
		Integer recordCount = 0;
		if (obj != null) {
			recordCount = new Integer(obj.toString());
		} else {
			recordCount = 0;
		}
		return recordCount;
	}
	
	@Override
	public int saveTmpTable(List tmpList) throws DaoLevelException {
		if (null != tmpList && tmpList.size() > 0) {
			TmpTableDto ttDto = null;
			for (int i = 0;i < tmpList.size(); i++) {
				ttDto = (TmpTableDto)tmpList.get(i);
				executeUpdateBySql("insert into rk_tmp_table(value1,value2) values("+ttDto.getValue1()+",'"+ttDto.getValue2()+"')");
			}
		}
		return 0;
	}
	
	@Override
	public int deleteTmpTable() throws DaoLevelException {
		  
		return executeUpdateBySql("delete from rk_tmp_table");
	}
	
	public static void main(String[] args) {
		String queryStr = " SELECT * FROM rk_dic_menu AS m RIGHT JOIN rk_role_menu AS r ON r.menu_id = m.menu_id WHERE 1=1 AND role_id=3  ";  
		int length = queryStr.indexOf("order by") > 0 ? queryStr
				.indexOf("order by") : queryStr.length();
				
		String hql = "select count(*) "
				+ queryStr.substring(queryStr.indexOf("FROM"), length);
		System.out.println("hql:"+hql);
		
	}
}
